package order

import (
	"awesomeProject/src/main/ApiHelpers"
	model "awesomeProject/src/main/Models"
	"awesomeProject/src/main/service"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

//todo 把service放进来了
type OrderHandler struct {
	orderService service.OrderService
}
//todo 没看懂语法
func NewOrderHandler(orderService service.OrderService) *OrderHandler{
	return &OrderHandler{orderService: orderService}
}

// 查询全部数据
func (orderHandler OrderHandler)GetAllOrder(c *gin.Context) {
	//调service
	allOrder, err := orderHandler.orderService.GetAllOrder()

	if err != nil {
		ApiHelpers.RespondJSON(c, 404, "未获取到数据", err)
	} else {
		ApiHelpers.RespondJSON(c, 200,"获取数据成功", allOrder)
	}
}

// 添加数据
func (orderHandler OrderHandler) AddNewOrder(c *gin.Context) {
	var order model.DemoOrder

	//order.Status = "sd"
	//order.Amount,_ = strconv.ParseFloat(c.PostForm("amount"), 64)
	//order.FileUrl = c.PostForm("file_url")
	//order.UserName = c.PostForm("user_name")
	//order.Status = c.GetString("orderNo")
	c.BindJSON(&order)
	fmt.Println("JSON数据")
	log.Print(&order)

	err := orderHandler.orderService.AddNewOrder(&order)
	if err != nil {
		ApiHelpers.RespondJSON(c, 404,"添加数据失败",nil)
	}
}

// 查询某一条数据
func (orderHandler OrderHandler) GetOneOrder(c *gin.Context) {
	orderNo := c.Params.ByName("orderNo")

	order ,err := orderHandler.orderService.GetOneOrder(orderNo)

	if err != nil {
		ApiHelpers.RespondJSON(c, 404,"查询数据失败", order)
	} else {
		ApiHelpers.RespondJSON(c, 200,"查询数据成功", order)
	}
}

// 修改某一条数据
func (OrderHandler OrderHandler)  UpdateOrder(c *gin.Context){

	var order model.DemoOrder
	c.BindJSON(&order)
	err := OrderHandler.orderService.UpdateOrder(&order)
	if err != nil {
		c.JSON(http.StatusBadRequest,gin.H{"error":err.Error()})
		return
	}

}
/*func (OrderHandler OrderHandler)  UpdatesOrder(c *gin.Context){
	orderNo := c.PostForm("orderNo")
	amount,_ := strconv.ParseFloat(c.PostForm("amount"), 64)
	status := c.PostForm("status")
	fileUrl := c.PostForm("fileUrl")


	err := OrderHandler.orderService.UpdatesOrder(orderNo, amount, status, fileUrl)
	if err != nil {
		c.JSON(http.StatusBadRequest,gin.H{"error":err.Error()})
		return
	}

}*/

// 删除某一条数据
//DeleteOrder(b *model.DemoOrder,orderNo string) (err error)
func (orderHandler OrderHandler) DeleteOrder(c *gin.Context) {
	orderNo := c.PostForm("orderNo")

	err := orderHandler.orderService.DeleteOrder(orderNo)

	if err != nil {
		ApiHelpers.RespondJSON(c, 404,"删除数据失败",nil)
	} else {
		ApiHelpers.RespondJSON(c, 200,"删除数据成功", nil)
	}
}

/*// DeleteTodo 删除待办事项
func DeleteTodo(c *gin.Context) {
	id, ok := c.Params.Get("id") //c.Params.Get()获取path(URL路径)参数,且获取的是string格式
	if !ok {
		c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
		return
	}
	err := Models.DeleteTodo(id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
	} else {
		c.JSON(http.StatusOK, gin.H{id: "deleted"})
	}
}*/